package com.smartstate.dataArchives.config.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.listener.api.RabbitListenerErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * <p>Title: 消息队列监听</p >
 * <p>Description: 监听信息</p >
 */

@Component
@Slf4j
public class RabbitMqConsumer {
  /**
   * 需要手动创建Queues
   * queues队列名称
   * @param message 传入参数
   */
//  @RabbitHandler
//  @RabbitListener(queues = "test.data.upstream", errorHandler = "rabbitListenerErrorHandler")
//  public void receive(Message message, Channel channel) throws Exception {
//    String s = new String(message.getBody(), "utf-8").trim();
//    System.out.println("rabbitMQ接收:"+s);
//  }
  /**
   * 自动创建Queues
   * queues队列名称
   * @param message 传入参数
   */
//  @RabbitHandler
//  @RabbitListener(queuesToDeclare = @Queue("test.data.upstream"), errorHandler = "rabbitListenerErrorHandler")
//  public void receive(Message message, Channel channel) throws Exception {
//    String s = new String(message.getBody(), "utf-8").trim();
//    System.out.println("rabbitMQ接收:"+s);
//  }

  /**
   * 自动创建Queues及Exchange
   * queues队列名称
   * Exchange交换器名称
   * @param message 传入参数
   */
  @RabbitHandler
  @RabbitListener(bindings = @QueueBinding(
          value=@Queue("test.data.upstream"),
          exchange = @Exchange("test")
  ), errorHandler = "rabbitListenerErrorHandler")
  public void receive(Message message, Channel channel) throws Exception {
    String s = new String(message.getBody(), "utf-8").trim();
    System.out.println("rabbitMQ接收:"+s);
  }

  @Bean
  public RabbitListenerErrorHandler rabbitListenerErrorHandler() {
    return (message, message1, e) -> {
      log.error(e.getMessage(), e);
      return null;
    };
  }
}
